package com.yystudy.aiagentbackend.start;

import com.yystudy.aiagentbackend.utils.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author: yp123
 * @since: 2025/6/16
 * 应用启动后输出接口文档地址
 * 触发时机：
 * 在 ApplicationContext 完全初始化后，before ApplicationReadyEvent
 * 所有 @Bean 已就绪，但应用尚未开始接收外部请求（Web 场景）
 */
@Slf4j
@Component
public class SetupLogRunner implements CommandLineRunner {

    /**
     * 应用启动后执行初始化逻辑
     * @param args incoming main method arguments
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        ApplicationContext applicationContext = BeanUtil.getApplicationContext();
        // 通过容器获取 application.yml 中定义的配置
        // 是否开启 swagger
        Boolean swaggerEnable = applicationContext.getEnvironment().getProperty("knife4j.enable", Boolean.class, false);
        // 应用端口
        Integer port = applicationContext.getEnvironment().getProperty("server.port", Integer.class, 8080);
        String hostAddress = null;
        try {
            hostAddress = InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException ignore) {
        }
        log.info("本地地址: http://localhost:{}", port);
        log.info("外部地址: http://{}:{}", hostAddress, port);
        if (Boolean.TRUE.equals(swaggerEnable)) {
            log.info("接口文档（knife4j）: http://{}:{}/api/doc.html", hostAddress, port);
        }
    }
}
